var crypto = require("crypto");
var express = require("express");
var bodyParser = require("body-parser");
var passport = require("passport");
var Strategy = require('passport-local').Strategy;

var router = express.Router();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
//引入数据模型
var user = require("../model/user");

passport.use("local", new Strategy(
    function(username, password, cb) {
        var md5 = crypto.createHash("md5");
        md5.update(password);
        var sign = md5.digest("hex");
        user.findOne({ username: username, password: sign }, function(err, doc) {
            if (doc) {
                //验证通过
                return cb(null, doc);
            } else {
                //验证不通过
                return cb(null, false);
            }
        });
    }
));
//序列化保存
passport.serializeUser(function(user, cb) {
    cb(null, user.id);
});
//解码序列化
passport.deserializeUser(function(id, cb) {
    user.findById(id, function(err, user) {
        cb(err, user);
    });
});

//转向登录
router.get("/login", function(req, res) {
    res.render("login", { layout: "login", login: true });
});
router.get('/register', function(req, res) {
    res.render("login", { layout: "login", login: false });
});

router.post("/login", urlencodedParser, function(req, res, next) {
    passport.authenticate("local", function(err, user, info) {
        if (err) {
            next(err);
        } else if (!user) {
            res.send({ code: 0, status: -1, message: "登录失败" })
        } else {
            req.logIn(user, function(err) {
                var returnTo = "/";
                if (err) {
                    next(err);
                } else {
                    if (req.session.returnTo) {
                        returnTo = req.session.returnTo;
                    }
                    // console.log(returnTo);
                    // res.redirect(returnTo);
                    res.send({ code: 0, status: 0, message: "登录成功", goto: returnTo });
                }
            });
        }
    })(req, res, next);
});
// 登出
router.get("/logout", function(req, res, next) {
    req.logOut();
    res.redirect("/login");
})
router.post("/register", urlencodedParser, function(req, res) {
    var username = req.body.username;
    var password = req.body.password;
    var md5 = crypto.createHash("md5");
    md5.update(password);
    var sign = md5.digest("hex");
    user.create({
        username: username,
        password: sign
    }, function(err, doc) {
        res.redirect("/login");
    });
});
module.exports = router;